<?php

/**
 * This is the model class for table "files".
 *
 * The followings are the available columns in table 'files':
 * @property integer $id
 * @property string $name
 * @property integer $size
 * @property string $type
 * @property string $extension
 * @property string $note
 * @property string $createdAt
 * @property string $updatedAt
 */
class File extends ActiveRecord {

	// Uploaded file
	public $file;
	
	private $_allowedExtensions = array(
		'zip',
		'rar',
		'7zip',
		'txt',
		'doc',
		'docx',
		'xls',
		'xlsx',
		'pdf',
		'exe',
		'ppt',
		'pptx',
	);

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return File the static model class
	 */
	public static function model($className = __CLASS__) {
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName() {
		return 'files';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules() {
		return array(
			array(
				'file',
				'file',
				'allowEmpty'=>FALSE,
				'on'=>'insert',
				'types'=>$this->_allowedExtensions,
			),
			array(
				'file',
				'file',
				'allowEmpty'=>TRUE,
				'on'=>'update',
				'types'=>$this->_allowedExtensions,
			),
			array('note', 'safe', 'on'=>'insert, update'),
			array('id, name, size, type, note', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations() {
		return array();
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels() {
		return array(
			'id'=>'ID',
			'name'=>'Name',
			'size'=>'Size',
			'type'=>'Type',
			'note'=>'Note',
			'file'=>'File',
			'createdAt'=>'Created At',
			'updatedAt'=>'Updated At',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search() {
		$criteria = new CDbCriteria;

		$criteria->compare('id', $this->id);
		$criteria->compare('name', $this->name, true);
		$criteria->compare('size', $this->size);
		$criteria->compare('type', $this->type, true);
		$criteria->compare('note', $this->note, true);

		return new CActiveDataProvider($this, array('criteria'=>$criteria));
	}

	public function behaviors() {
		$behaviors = parent::behaviors();
		$behaviors['fileBehavior'] = array(
			'class'=>'FileARBehavior',
			'attribute'=>'file',
			'extension'=>implode(', ', $this->_allowedExtensions),
			'prefix'=>'',
			'relativeWebRootFolder'=>'files/files',
		);
		return $behaviors;
	}

	public function beforeSave() {
		$file = CUploadedFile::getInstance($this, 'file');
		if ($file) {
			$this->name = $file->name;
			$this->size = $file->size;
			$this->type = $file->type;
			$this->extension = $file->extensionName;
		}
		return parent::beforeSave();
	}

}